from django.shortcuts import render
import random

from .models import HotBook,StaticPress,StaticType,Type
from django.http import JsonResponse
import logging
logger = logging.getLogger(__name__)
# from rest_framework_mongoengine.serializers import DocumentSerializer

import pymongo
client = pymongo.MongoClient("211.87.227.243",27017)
db = client.get_database("bookcrawl")
books = db.get_collection("books")
dang_link = db.get_collection("dang_links")
amazon_link = db.get_collection("amazon_links")
bookschina_link = db.get_collection("bookschina_links")
top_book = db.get_collection("top_book")
presses = db.get_collection("presses")
types = db.get_collection("types")

# Create your views here.

def index(request):
    types = books.find_one({"type": "all"})["typeset"]
    typedata = [Type(i,i) for i in types]

    return render(request, 'blog/base_page.html',context=dict(
        has_search_table = True,
        has_form = True,
        search_api = "search_title",
        # head_text = "",
        typedata = typedata,
        show_text = f"总数据量:{books.count()}",
    ))

def hot(request):
    cur = top_book.find({"hot": {"$gt": 12}})
    res = []

    for src in cur:
        b = HotBook()
        b.title = src["title"]
        b.hot = src["hot"]
        if b.hot> 22:
            b.label = "btn-danger"
        elif b.hot > 17:
            b.label = "btn-warning"
        elif b.hot>15:
            b.label = "btn-primary"
        elif b.hot>13:
            b.label = "btn-info"
        else:
            b.label = "btn-success"
        res.append(b)

    random.shuffle(res)

    return render(request,'blog/base_page.html',context=dict(
        data = res,
        show_text = "根据编辑推荐...还算准吧",
        head_text = "-HOT"
    ))


def strange(request):
    return render(request,"blog/base_page.html",context=dict(
        has_show_table=  True,
        directly_search_api = "strange",
        head_text = "-ST",
        show_text = "指在爬取过程中捕获到的特殊的商品，这并不常见",
    ))

def serializeBook(books,filter_strange = True,select_strange = False):
    for i,book in enumerate(books):
        res = book
        if filter_strange:
            if res.get("author",None) is None and res.get("press",None) is None:
                continue

        if select_strange:
            if res.get("author", None) is not None or res.get("press", None) is not None:
                continue

        res.pop("_id")

        if "link" not in res:
            continue

        if "price" in res:
            res["price"] = float(res["price"])
        if "star" in res:
            res["star"] = float(res["star"])

        if "title" in res:
            res["title"] = f'<a style="color: black;">{res["title"]}</a>'
        # res["title"] = f'<a data-toggle="popover-{i}" title="江雪" data-content="千山鸟飞绝，万径人踪灭。">.tooltip-primary</a>'


        res["field"] = f'<a href="{res["link"]}">{res["field"]}</a>'

        res = dict(res)
        # res["selector"] = f'[data-toggle="popover-{i}"]'
        yield res

def search_page(request,title):
    '''
    返回页面，从热门页面中的按钮跳转过来，之后可以考虑从Link的图中跳转过来
    :param request:
    :param title:
    :return:
    '''
    return render(request,"blog/base_page.html",context=dict(
        has_show_table = True,
        directly_search_api = title
    ))

def filter_build(min_price,max_price,min_star,max_star):
    res = dict()

    if min_price.isdigit():
        res.setdefault("price", {})
        res["price"]["$gte"] = int(min_price)
    if max_price.isdigit():
        res.setdefault("price", {})
        res["price"]["$lte"] = int(max_price)
    if min_star.isdigit():
        res.setdefault("star", {})
        res["star"]["$gte"] = int(min_star)
    if max_star.isdigit():
        res.setdefault("star", {})
        res["star"]["$lte"] = int(max_star)

    return res

def search_title(request,title):
    '''
    用来搜索标题，返回Json
    :param request:
    :param title:
    :return:
    '''
    if title == "strange":
        return search_strange()

    if request.method == "POST":
        dq = request.POST
        title = dq["content"]
        min_price = dq["price-min"]
        max_price = dq["price-max"]
        min_star = dq["star-min"]
        max_star = dq["star-max"]
        type = dq["type"]
        num_filter = filter_build(min_price, max_price, min_star, max_star)

        if type != "--":
            type_filter = dict(
                re_type=type,
            )
        else:
            type_filter = dict()
    else:
        num_filter = dict()
        type_filter = dict()

    search_dict = {"$text": {"$search": title}}
    if len(title) == 0:
        search_dict = dict()


    search_dict.update(num_filter)
    search_dict.update(type_filter)

    cur = books.find(search_dict,
                     {"score": {"$meta": "textScore"}})  # .limit(100).sort("search_title")
    se = serializeBook(cur)

    res = []
    for i, s in enumerate(se):
        res.append(s)

    resp = dict(
        result="success",
        data=res,
        message="",
        pager={
            "page": 1,
            "recTotal": 50,
            "recPerPage": 10,
        }
    )
    return JsonResponse(resp, safe=False)

def search_strange():
    '''
    搜索奇葩的页面
    :param request:
    :param req:
    :return:
    '''
    # cur = books.find({"press": {"$exist":False}, "author": None})
    cur = books.find({"press": {"$exists":False}})
    se = serializeBook(cur, False, False)
    se = list(se)
    se = random.choices(se,k=100)
    # print(len(se))
    resp = dict(
        result="success",
        data=se,
        message="",
        pager={
            "page": 1,
            "recTotal": 50,
            "recPerPage": 10,
        }
    )
    return JsonResponse(resp, safe=False)


def press(request):
    cur = presses.find({"count": {"$exists": True,"$gt":20}}).sort([("count", -1)])#.limit(50)

    result = StaticPress()

    for res in cur:
        result.press.append(res["re_press"])
        result.count.append(res["count"])

    cur = types.find().sort([("count",-1)])
    tres = StaticType()
    for res in cur:
        tres.type.append(res["_id"])
        tres.count.append(res["count"])


    # print(result.press)
    return render(request,"blog/base_page.html",context=dict(
        head_text = "-CT",
        show_text = "简单的统计一些数据...",
        static_press_data = result,
        static_type_data = tres,
        show_press_hist = True,
    ))

def about(request):
    return render(request,"blog/base_page.html",context=dict(
        show_about = True,
        head_text = "-ABOUT",
        show_text = "关于..关于"
    ))